/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import healthcare.coursework.model.Outlet;
import healthcare.coursework.model.Specialization;
import healthcare.coursework.model.Users;
import healthcare.coursework.service.UserService;
import java.sql.Timestamp;
import java.util.Date;
import javax.ejb.EJBException;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

/**
 *
 * @author Administrator
 */
public class AddStaff extends GenericAutowireComposer {

    private Combobox branch;
    private Textbox username;
    private Textbox password;
    private Textbox confirmPassword;
    private Textbox fullName;
    private Datebox birthdate;
    private Radiogroup gender;
    private Radiogroup role;
    private Textbox phone;
    private Textbox address;
    private Textbox email;
    private Row labFunction;
    private Combobox typeOfLaboratory;
    private Row specFunction;
    private Combobox specification;
    private Window self;
    private Users u;
    private UserService userService = util.Utility.getUtility().getUserService();

    private void setConstraint() {
        username.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateUsername(cmpnt, o);
            }
        });

        password.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validatePassword(cmpnt, o);
            }
        });
        confirmPassword.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateConfirmPass(cmpnt, o);
            }
        });

        fullName.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateFullname(cmpnt, o);
            }
        });

        birthdate.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateBirthDate(cmpnt, o);
            }
        });

        address.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateAddress(cmpnt, o);
            }
        });

        phone.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validatePhone(cmpnt, o);
            }
        });
        email.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateEmail(cmpnt, o);
            }
        });
    }

    public void validateEmail(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Please enter email");
        }
        if (!s.matches("^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\\.)+([A-Za-z0-9]{2,4}|museum)$")) {
            throw new WrongValueException(comp, "Invalid email");
        }
        if (userService.isEmailExisted(s)) {
            throw new WrongValueException(comp, "Email existed! Please choose another Email!");
        }
    }

    private void validatePassword(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Please  new password");
        }
        if (!s.matches("^\\w{3,20}$")) {
            throw new WrongValueException(comp, "Password must be 3-20 alphanumeric characters");
        }
    }

    private void validateConfirmPass(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        if (!s.equals(password.getValue())) {
            throw new WrongValueException(comp, "Confirm password and password are not match");
        }
    }

    public void validateUsername(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Username cannot be empty");
        }
        if (!s.matches("^[a-zA-Z][\\w]{5,19}$")) {
            throw new WrongValueException(comp, "Username must be 6-20 alphanumeric characters");
        }
        if (userService.findUser(s.trim()) != null) {
            throw new WrongValueException(comp, "UserName existed! Please chooses another UserName!");
        }

    }

    private void validateFullname(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Fullname cannot be empty");
        }
    }

    private void validateJob(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Job cannot be empty");
        }
    }

    private void validateBirthDate(Component comp, Object value) throws WrongValueException {
        Date d = (Date) value;
        if (d == null) {
            throw new WrongValueException(comp, "Birthdate cannot be empty");
        }
        if (d.after(new Date())) {
            throw new WrongValueException(comp, "Birthdate must be less than current date!!!");
        }
    }

    private void validateAddress(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Address cannot be empty");
        }
    }

    private void validatePhone(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Phone cannot be empty");
        }
    }

    public void onReset(Event e) {
        username.setValue("");
        password.setValue("");
        confirmPassword.setValue("");
        fullName.setValue("");
        address.setValue("");
        phone.setValue("");
        birthdate.setValue(new Date());
        email.setValue("");
    }

    public void onSubmit(Event e) {
        try {
            System.out.println(username.getValue());
            u.setUsername(username.getValue());
            u.setPassword(password.getValue());
            u.setFullName(fullName.getValue());
            u.setAddress(address.getValue());
            u.setPhone(phone.getValue());
            u.setGender(gender.getSelectedItem().getValue());
            u.setDateOfBirth(new Timestamp(birthdate.getValue().getTime()));
            u.setEmail(email.getValue());
            if(role.getSelectedItem().getValue().equals("Laboratory"))
            {
                u.setTypeOfLaboratory((String) typeOfLaboratory.getSelectedItem().getLabel());
                System.out.println((String) typeOfLaboratory.getSelectedItem().getLabel());
            }
            u.setEnabled(true);
            userService.create(u, role.getSelectedItem().getValue());
            Messagebox.show("New staff has been inserted!", "Information", Messagebox.OK, Messagebox.INFORMATION);
            self.onClose();
            Executions.sendRedirect("TrackStaff.do");
        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void onClose(Event e) {
        self.onClose();
        Executions.sendRedirect("TrackStaff.do");
    }

    public void onRole(Event e) {
        switchFunction();
    }

    private void switchFunction() {
        System.out.println(role.getSelectedItem().getValue());
        if (role.getSelectedItem().getValue().equals("Laboratory")) {
            labFunction.setVisible(true);
            specFunction.setVisible(false);
        } else {
            labFunction.setVisible(false);
            specFunction.setVisible(true);
        }
    }

    private void setInfo() {
        branch.setModel(new ListModelList(userService.outlets()));
        specification.setModel(new ListModelList(userService.specializations()));
        switchFunction();
        setConstraint();
    }

    public void onLoadForm(Event e) {
        u = new Users();
        setInfo();
    }

    public void onSetBranchInfo(Event e) {
        Outlet o = (Outlet) branch.getSelectedItem().getValue();
        System.out.println("Set information :"+o.getOutletName());
        u.setOutlet(o);
    }
       public void onSetSpecInfo(Event e) {
        Specialization s = (Specialization) specification.getSelectedItem().getValue();

        u.setSpecialization(s);
    }
}
